import json
import time
import urllib

import requests


def post_api(url, data):
    headers = {
        'Accepat':
        'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Language':
        'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4',
        'User-Agent':
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'
    }
    resp = requests.post(headers=headers, url=url, data=data)
    resp.raise_for_status()
    return resp.json()


def get_owhat_ranking_page(ID, page=1):
    url = 'https://m.owhat.cn/api'
    payload = {
        "cmd_s":
        "shop.goods",
        "cmd_m":
        "findrankingbygoodsid",
        "v":
        "1.5.6L",
        "client":
        json.dumps({
            "platform": "mobile",
            "version": "5.5.0",
            "deviceid": "444c8302-9134-1396-b7e1-6359f024231a",
            "channel": "owhat"
        }),
        "token":
        "c53066c474bf49f91a1a79be6d92917a",
        "data":
        json.dumps({
            "goodsid": str(ID),
            "pagenum": page,
            "pagesize": 100
        })
    }
    # url += '&'.join([f'{k}={v}' for k, v in payload.items()])
    resp = post_api(url, data=payload)
    return resp


def get_owhat_ranking(ID):
    max_req = 20
    page = 1
    rankinglist = []
    while max_req > 0:
        res = get_owhat_ranking_page(ID, page)
        rl = res['data']['rankinglist']
        if not rl:
            return rankinglist
        rankinglist.extend(rl)
        page += 1
        max_req -= 1
    return rankinglist


def get_fund_info(ID):
    ranking = get_owhat_ranking(ID)
    return {
        "raised": round(sum(float(i['amount']) for i in ranking), 2),
        "backers": len(ranking),
    }


if __name__ == "__main__":
    print(get_fund_info(105412))
